<template>
  <div class="maintenance-progress">
    <div class="content-item-tittle">维保进度</div>
    <el-row class="search-form-wrap">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
        <el-form-item>
          <el-select
            filterable
            @change="getData(1)"
            v-model="formInline.fireTTypes"
            placeholder="请选择警情类型"
          >
            <el-option label="全部任务" value></el-option>
            <el-option label="维保巡查" value="1"></el-option>
            <el-option label="保养" value="2"></el-option>
            <el-option label="单点测试" value="3"></el-option>
            <el-option label="联动测试" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            @change="getData(1)"
            v-model="formInline.time"
            type="month"
            format="yyyy-MM"
            value-format="yyyy-MM"
            placeholder="请选择月度"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </el-row>
    <div class="maintenance-progress-content">
      <el-row type="flex" justify="space-between" class="maintenTimeDimension-echarts-header">
        <el-col :span="4">
          <p
            class="maintenance-progress-num"
          >{{ (resultData.totalFinishCount || 0) + (resultData.totalUnfinishCount || 0)}}</p>
          <p class="maintenance-progress-text">任务总数</p>
        </el-col>
        <el-col :span="4">
          <p
            class="maintenance-progress-num"
            style="color:#47CFAD"
          >{{ resultData.totalFinishCount || 0 }}</p>
          <p class="maintenance-progress-text">完成任务数</p>
        </el-col>
        <el-col :span="4">
          <p
            class="maintenance-progress-num"
            style="color:#FFB32D"
          >{{ resultData.totalUnfinishCount || 0 }}</p>
          <p class="maintenance-progress-text">未完成任务数</p>
        </el-col>
        <el-col :span="4">
          <p class="maintenance-progress-num" style="color:#4FBFE9">{{ completionRate }}</p>
          <p class="maintenance-progress-text">任务完成率</p>
        </el-col>
      </el-row>
      <!-- 分析结果图 -->
      <div id="maintenance-progress-echarts" class="maintenance-progress-echarts"></div>
      <!-- <div class="maintenance-button">
        <div
          class="maintenance-button-item"
          v-for="item in dataList"
          :key="item"
          :style="'width:'+ 100/buttonLength +'%;'"
        >
          <div class="gotoMaintenanceDetias" @click="jumpOtherPage(item)">详情</div>
        </div>
      </div>-->
    </div>
  </div>
</template>

<script>
import { getMaintainAnalysisByTime } from "@/api/maintence";
import util from "@/utils/util";
export default {
  name: "MaintenanceProgress",
  props: {
    organizationId: {
      default() {
        return undefined;
      }
    }
  },
  data() {
    return {
      resultData: {
        totalFinishCount: 1,
        totalUnfinishCount: 2
      },
      dataList: [],
      completionRate: "55%",
      res: {},
      formInline: {
        fireTTypes: "",
        time: util.ilinkTimeformat.format(new Date(), "yyyy-MM")
      },
      pickerOptions: {
        disabledDate(time) {
          let _now = Date.now();
          return time.getTime() > _now;
        }
      }
    };
  },
  created() {
    this.getData(1);
  },
  methods: {
    getData(type) {
      let that = this;
      getMaintainAnalysisByTime({
        orgId: this.organizationId || this.$store.state.userinfo.org.id,
        dateType: 1,
        date: that.formInline.time,
        period: 0,
        workType: that.formInline.fireTTypes || 0
      }).then(res => {
        if (res.status === 200) {
          this.resultData = res.data;
          this.completionRate = this.calcCompletionRate(
            res.data.totalFinishCount,
            res.data.totalFinishCount + res.data.totalUnfinishCount
          );
          this.renderAnalusisEcharts(res.data.details);
        }
      });
    },
    jumpOtherPage(type) {
      let that = this;
      let params = {
        level: 2, // level  页面跳转显示   1-多单位   2-单单位
        // orgId: that.organizationId, // 单位编码
        time: that.formInline.time, // 维保进度时间
        fireTTypes: that.formInline.fireTTypes, //维保状态
        systomType: type //维保系统类别
      };

      if (that.organizationId) {
        params.level = 1;
        params["orgId"] = Number(that.organizationId);
      }

      this.$router.push({
        name:'maintenanceTask',
        params
      })
    },
    // 渲染柱状图
    renderAnalusisEcharts(res) {
      let that = this;
      let data = res;
      let xAxisData = [];
      let doneData = [];
      let undoneData = [];
      let completionRateData = [];

      for (let i = 0, len = data.length; i < len; i++) {
        xAxisData.push(data[i].fireSystemName);
        doneData.push(data[i].finishCount);
        undoneData.push(data[i].unfinishCount);
        completionRateData.push(
          that.calcCompletionRate(
            data[i].finishCount,
            data[i].finishCount + data[i].unfinishCount
          )
        );
      }
      that.dataList = xAxisData;
      that.buttonLength = that.dataList.length;
      let option_echart = {
        tooltip: {
          trigger: "axis",
          formatter: function(params) {
            let str = `${params[0].axisValueLabel}<br/>完成率：${
              completionRateData[params[0].dataIndex]
            }<br/>${params[0].marker}未完成任务：${params[0].value}<br/>${
              params[1].marker
            }已完成任务：${params[1].value}`;
            return str;
          }
        },
        color: ["#FFB32D", "#47CFAD"],
        legend: {
          top: "0",
          data: ["未完成", "已完成"],
          itemGap: 10,
          itemWidth: 15,
          itemHeight: 12
        },
        grid: {
          right: "5%",
          left: "7%",
          bottom: "25%"
        },
        dataZoom: [
          {
            type: "slider",
            show: xAxisData.length > 4 ? true:false,
            /* start: 0,
            end: 50, */
            endValue: 5,
            height: 14,
            borderColor: "transparent",
            backgroundColor: "#e2e2e2",
            // 拖拽手柄样式 svg 路径
            handleIcon:
              "M512 512m-208 0a6.5 6.5 0 1 0 416 0 6.5 6.5 0 1 0-416 0Z M512 192C335.264 192 192 335.264 192 512c0 176.736 143.264 320 320 320s320-143.264 320-320C832 335.264 688.736 192 512 192zM512 800c-159.072 0-288-128.928-288-288 0-159.072 128.928-288 288-288s288 128.928 288 288C800 671.072 671.072 800 512 800z",
            handleColor: "#aab6c6",
            handleSize: 20,
            handleStyle: {
              borderColor: "#aab6c6",
              shadowBlur: 4,
              shadowOffsetX: 1,
              shadowOffsetY: 1,
              shadowColor: "#e5e5e5"
            },
            /* maxSpan: "70", */
            textStyle:{
              color:"transparent"
            }
          },
          {
            type: "inside",
            start: 50,
            end: 100
          }
        ],
        xAxis: [
          {
            type: "category",
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              lineStyle: {
                color: "#999"
              }
            },
            axisLabel: {
              interval: 0,
              rotate: 0,
              formatter: function(params) {
                var newParamsName = ""; // 最终拼接成的字符串
                var paramsNameNumber = params.length; // 实际标签的个数
                var provideNumber = 7; // 每行能显示的字的个数
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
                /**
                 * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
                 */
                // 条件等同于rowNumber>1
                if (paramsNameNumber > provideNumber) {
                  /** 循环每一行,p表示行 */
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = ""; // 表示每一次截取的字符串
                    var start = p * provideNumber; // 开始截取的位置
                    var end = start + provideNumber; // 结束截取的位置
                    // 此处特殊处理最后一行的索引值
                    if (p == rowNumber - 1) {
                      // 最后一次不换行
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      // 每一次拼接字符串并换行
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr; // 最终拼成的字符串
                  }
                } else {
                  // 将旧标签的值赋给新标签
                  newParamsName = params;
                }
                //将最终的字符串返回
                return newParamsName + "\n" + "{a|详情}";
              },
              rich: {
                a: {
                  lineHeight: 30,
                  align: "center",
                  color: "#8890ab",
                  borderColor: "#8890ab",
                  borderWidth: "1px",
                  padding: [5, 10, 5, 10]
                }
              }
            },
            data: xAxisData,
            triggerEvent: true
          }
        ],
        yAxis: [
          {
            type: "value",
            name: "任务数",
            minInterval: 1,
            axisLine: {
              show: false,
              lineStyle: {
                color: "#999"
              }
            },
            nameTextStyle: {
              color: "#999"
            },
            splitArea: {
              show: false
            },
            axisTick: {
              show: false
            }
          }
        ],
        series: [
          {
            data: undoneData,
            name: "未完成",
            stack: "one",
            type: "bar",
            barMaxWidth:50//最大宽度
          },
          {
            data: doneData,
            name: "已完成",
            stack: "one",
            type: "bar",
            barMaxWidth:50,//最大宽度
            label: {
              show: true,
              position: "top",
              color: "#4CA4FE",
              fontSize: 16,
              formatter: function(params) {
                return completionRateData[params.dataIndex];
              }
            }
          }
        ]
      };

      that.$echarts
        .init(document.getElementById("maintenance-progress-echarts"))
        .setOption(option_echart, true);
      that.$echarts
        .init(document.getElementById("maintenance-progress-echarts"))
        .on("click", function(params) {
          if (params.componentType == "xAxis") {
            that.jumpOtherPage(params.value);
          }
        });
    },
    // 计算完成率
    calcCompletionRate(num, total) {
      let result = util.accDiv(num, total);

      result = Math.floor(result * 10000) / 100;
      return (result || 0) + "%";
    }
  }
};
</script>
<style lang="scss">
.maintenance-progress {
  .search-form-wrap {
    float: right;
    margin-top: -34px;
  }
  .maintenance-progress-content {
    padding: 42px 20px;
    margin-top: 30px;
    height: calc(100% - 51px);
    border: 1px solid #e1e1e1;
    .el-col-4 {
      text-align: center;
    }
  }
  .maintenance-progress-echarts {
    margin-top: 30px;
    // width: 100%;
    height: 480px;
  }
  .maintenance-progress-num {
    font-size: 48px;
    font-weight: bold;
    color: #4ca4fe;
  }
  .maintenance-progress-text {
    font-size: 16px;
    color: #8890ab;
  }
  .maintenance-button {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    width: 88%;
    margin-left: 7%;
  }
  .gotoMaintenanceDetias {
    margin-left: calc(50% - 40px);
    width: 80px;
    height: 32px;
    background: #ffffff;
    border: 1px solid #8890ab;
    border-radius: 4px;
    line-height: 32px;
    color: #8890ab;
    cursor: pointer;
  }
  .maintenance-button-item {
    float: left;
    text-align: center;
  }
}
</style>